package com.tiendung.otalunch;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.tiendung.otalunch.AsyncFacebookRunner.RequestListener;
import com.tiendung.otalunch.Facebook.DialogListener;

public class FacebookActivity extends Activity
{

	private OtaLunchDatabase db;
	private static final String APP_ID = "101659683252789";
	private final ArrayList<Friend> friends = new ArrayList<Friend>();
	private Facebook mFacebook;
    private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"};
    
    private TextView mLabel;
    private Button mLogoutButton;
    
    private Activity baseActivity;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.facebook);
	    baseActivity = this;
	    
	    this.db = new OtaLunchDatabase(this);
	       
	    mFacebook = new Facebook(APP_ID);	    
	    
	    mLabel = (TextView) findViewById(R.id.facebook_label);
	    mLogoutButton = (Button) findViewById(R.id.facebook_logout);
	    
	    mLogoutButton.setOnClickListener(new View.OnClickListener() {             
        	public void onClick(View v) 
        	{                 
        		if (mFacebook.isSessionValid()) {
                    AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
                    asyncRunner.logout(baseActivity, new LogoutRequestListener());
                } 
        		else
        		{
        			mFacebook.authorize(baseActivity, PERMISSIONS, new LoginDialogListener());
        		}
        	}
        }); 
	}
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mFacebook.authorizeCallback(requestCode, resultCode, data);
    }
	
    private final class LoginDialogListener implements DialogListener {

        public void onComplete(Bundle values) {
        	final String name;
        	final String id;
        	byte[] thedigest = null;			
        	
        	try {    
        		JSONObject json = new JSONObject(mFacebook.request("me"));
                name = json.getString("name");
                id = json.getString("id");
                
        		mLabel.post(new Runnable() {  
        			public void run() {  
        				mLabel.setText("Welcome " + name);
        			}
        		});
        		
        		mLogoutButton.post(new Runnable() {  
        			public void run() {  
        				mLogoutButton.setText("Logout");
        			}
        		});
        		
        		String response = mFacebook.request("me/friends");
        		json = new JSONObject(response);        		
        		
    			try
    			{
    				byte[] bytesOfMessage = response.getBytes("UTF-8");
    				MessageDigest md = MessageDigest.getInstance("MD5");
    				thedigest = md.digest(bytesOfMessage);
    			
                    JSONArray d = json.getJSONArray("data");
                    int l = (d != null ? d.length() : 0);
                    
                    for (int i=0; i<l; i++) {
                        JSONObject o = d.getJSONObject(i);
                        String friend_name = o.getString("name");
                        String friend_id = o.getString("id");
                        Friend f = new Friend();
                        f.id = friend_id;
                        f.name = friend_name;
                        friends.add(f);

                        db.insert_friend_id(id, friend_id, friend_name);
                    }
                    
                    db.remove_facebook_id();
                    db.insert_facebook_id(id, name, new String(thedigest));
                    
    			}    			
    			catch (Exception e) {}    
                
        	}
        	catch (Exception e) {}        	 
        }

        public void onFacebookError(FacebookError error) { }
        public void onError(DialogError error) { }
        public void onCancel() { }
    }
        
    private class LogoutRequestListener implements RequestListener {

        public void onComplete(String response, Object state) {
            FacebookActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    friends.clear();
                    db.remove_facebook_id();
                    db.remove_friends();
                    
                    mLabel.post(new Runnable() {  
            			public void run() {  
            				mLabel.setText("Welcome to FaceConnect function");
            			}
            		});
                                		
            		mLogoutButton.post(new Runnable() {  
            			public void run() {  
            				mLogoutButton.setText("Login");
            			}
            		});     
                    
                }
            });
        }

		public void onIOException(IOException e, Object state) { }
		public void onFileNotFoundException(FileNotFoundException e, Object state) { }
		public void onMalformedURLException(MalformedURLException e, Object state) { }
		public void onFacebookError(FacebookError e, Object state) { }
    }
}
